package strings;

/**
 * 剑指 Offer 58 - II. 左旋转字符串
 * <p>
 * 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如，输入字符串"abcdefg"和数字2，该函数将返回左旋转两位得到的结果"cdefgab"。
 */
public class O58_ReverseLeftWords {
    public String reverseLeftWords(String s, int n) {
        StringBuilder sb = new StringBuilder(s);
        reverseString(sb, 0, n - 1);
        reverseString(sb, n, sb.length() - 1);
        reverseString(sb, 0, sb.length() - 1);
        return sb.toString();
    }

    private void reverseString(StringBuilder sb, int left, int right) {
        while (left < right) {
            char temp = sb.charAt(left);
            sb.setCharAt(left, sb.charAt(right));
            sb.setCharAt(right, temp);
            left++;
            right--;
        }
    }

    public String reverseLeftWords_API(String s, int n) {
        return s.substring(n) + s.substring(0, n);
    }


    public static void main(String[] args) {
        O58_ReverseLeftWords solution = new O58_ReverseLeftWords();
        System.out.println(solution.reverseLeftWords("asdfgh", 2));
        System.out.println(solution.reverseLeftWords_API("asdfgh", 2));
    }
}
